
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
/**
 * @param {number[]} prices
 * @return {number}
 */

/**
  * 求股票买卖最佳利润值
  * 1、方法1: 遍历数组，求出他所有上涨的趋势价格，就是它最大的利润
  */
const maxProfit = function (prices) {
  if (!prices || prices.length < 2) {
    return 0
  }

  const len = prices.length - 1

  return prices.reduce((cur, next, index) => {
    if (index < len && prices[index] < prices[index + 1]) {
      cur += prices[index + 1] - prices[index]
    }
    return cur
  }, 0)
}

// 代码优化

const maxProfit1 = function (prices) {
  return prices.reduce((profit, price, i, prices) => {
    return prices[i + 1] > prices[i] ? (profit += prices[i + 1] - prices[i]) : profit
  }, 0)
}

// 代码优化

const maxProfit2 = function (prices) {
  return prices.reduce((profit, price, i, prices) => {
    return i > 0 && prices[i] > prices[i - 1] ? (profit + prices[i] - prices[i - 1]) : profit
  }, 0)
}

var intersect = function (nums1, nums2) {
  nums1.sort((a, b) => a - b)
  nums2.sort((a, b) => a - b)

  let i = 0
  let j = 0
  const len1 = nums1.length
  const len2 = nums2.length
  const result = []

  while ((i < len1) && (j < len2)) {
    if (nums1[i] === nums2[j]) {
      result.push(nums1[i])
      ++i
      ++j
    } else {
      nums1[i] < nums2[j] ? ++i : ++j
    }
  }

  return result
}

const arr = [1, 2, 2, 1]
const arr1 = [2, 2]
console.log(intersect(arr, arr1))

module.exports = {
  maxProfit,
  maxProfit1,
  maxProfit2
}
